package zdream.pmfield.stage.effect;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

import zdream.pmfield.data.foe.MoveAdditionalEffects;
import zdream.pmfield.stage.buff.foe.FoeStageBuff;
import zdream.pmfield.stage.director.HookStore;
import zdream.pmfield.stage.director.HookType;
import zdream.pmfield.stage.director.Hooks;
import zdream.pmfield.stage.message.FoeRemoveBuffMessage;
import zdream.pmfield.stage.object.FoeActor;

import static zdream.pmfield.data.foe.MoveAdditionalEffects.E_REMOVE_BUFF;

/**
 * @author Zdream
 * @date 2023-12-08
 * @since 0.0.1
 */
public class RemoveBuffEffect extends AbstractEffect {
	private static final String DESC_KEY_BUFFS = MoveAdditionalEffects.K_REMOVE_BUFF_BUFFS;
	private static final String DESC_KEY_TARGET = MoveAdditionalEffects.K_REMOVE_BUFF_TARGET;
	public final EffectTarget target;
	private final String[] buffs;

	public RemoveBuffEffect(MoveAdditionalEffects.EffectDescription description) {
		super(E_REMOVE_BUFF);

		final Map<String, ?> parsed = MoveAdditionalEffects.parse(description);
		Objects.requireNonNull(parsed);

		buffs = Objects.requireNonNull((String[]) parsed.get(DESC_KEY_BUFFS));
		target = EffectTarget.valueOf((String) parsed.get(DESC_KEY_TARGET));
	}

	@Override
	public void init(Function<HookType, HookStore.HookHandlerBuilder> onHook) {
		onHook.apply(HookType.AFTER_EXECUTE_ATTACK)
				.handle(this::removeBuffToFoesAfterAttack)
				.buildAndSave();
	}

	protected void removeBuffToFoesAfterAttack(Hooks.HookContext rawContext) {
		final Hooks.AttackHookContext hooks = rawContext.as();
		for (FoeActor foe : affectedFoesWithTarget(hooks.attackContext, target)) {
			final List<FoeStageBuff> buffsNeedRemoved = foe.findBuffs(buffs);

			for (FoeStageBuff buff : buffsNeedRemoved) {
				foe.removeBuff(buff);
				pushMessage(foe.stage, new FoeRemoveBuffMessage(buff));
			}
		}
	}
}
